package org.skydiveapphd;

import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Date;

import org.skydiveapphd.interfaces.RigReminderNotifier;
import org.skydiveapplibrary.R;
import org.skydiveapplibrary.data.RigReminder;
import org.skydiveapplibrary.data.TimeUnit;
import org.skydiveapplibrary.data.RigReminder.DueStatus;
import org.skydiveapplibrary.ui.FormatUtility;
import org.skydiveapplibrary.ui.TimeIntervalDialog;
import org.skydiveapplibrary.ui.TimeIntervalDialog.OnTimeIntervalSetListener;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Fragment;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

public class RigReminderEditActivity extends Fragment
{
	// data
	private int interval;
	private TimeUnit intervalUnit;
	private Date lastDoneDate;
	private String name;
	private Boolean isEdit = false;
	

	public static RigReminderEditActivity newInstance(Bundle args) 
	{
		RigReminderEditActivity f = new RigReminderEditActivity();
		f.setArguments(args);
		return f;
	}
	
	
	// listeners
	private OnClickListener saveListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			save();
		}
	};
	private OnClickListener cancelListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			getFragmentManager().popBackStack();
		}
	};
	private OnClickListener intervalEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			showIntervalDialog();
		}
	};
	private OnTimeIntervalSetListener intervalSetListener = new OnTimeIntervalSetListener()
	{
		@Override
		public void onTimeIntervalSet(TimeIntervalDialog dialog, int interval,
				TimeUnit timeUnit)
		{
			updateInterval(interval, timeUnit);
		}
	};
	private OnClickListener dateEditListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			showDateDialog();
		}
	};
	private OnDateSetListener dateSetListener = new OnDateSetListener()
	{
		@Override
		public void onDateSet(DatePicker dialog, int year, int month, int day)
		{
			Calendar cal = Calendar.getInstance();
			cal.set(year, month, day);
			updateLastDoneDate(cal.getTime());
		}
	};
	private OnClickListener deleteListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			delete();
		}
	};
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		loadData();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	    		Bundle savedInstanceState)
	{	
	    // Inflate the layout for this fragment
	    return inflater.inflate(R.layout.rig_reminder_edit_view, container, false);
	}
	
	@Override
    public void onResume()
    {
    	super.onResume();
    	
		// init ui
		initializeUI();
    }
	
	private void loadData()
	{
		// get data
		isEdit = getArguments().getBoolean(Constants.EXTRA_RIG_REMINDER_IS_EDIT, false);
		name = (getArguments().containsKey(Constants.EXTRA_RIG_REMINDER_NAME)) ?
				getArguments().getString(Constants.EXTRA_RIG_REMINDER_NAME) : "";
		interval = getArguments().getInt(Constants.EXTRA_RIG_REMINDER_INTERVAL, 0);
		intervalUnit = (getArguments().containsKey(Constants.EXTRA_RIG_REMINDER_INTERVAL_UNIT)) ?
				(TimeUnit)getArguments().getSerializable(Constants.EXTRA_RIG_REMINDER_INTERVAL_UNIT) : TimeUnit.Days;
		lastDoneDate = (getArguments().containsKey(Constants.EXTRA_RIG_REMINDER_LAST_COMPLETED_DATE)) ?
				(Date)getArguments().getSerializable(Constants.EXTRA_RIG_REMINDER_LAST_COMPLETED_DATE) : new Date();
	}
	
	private void initializeUI()
	{
		// set header text
		TextView headerTextView = (TextView) getActivity().findViewById(R.id.EditHeaderTextView);
		headerTextView.setText(R.string.rig_reminder_header);
		
		// set name
		EditText dField = (EditText) getActivity().findViewById(R.id.RigReminderDescriptionField);
		dField.setText(name);
		
		// init interval field
		TextView iField = (TextView) getActivity().findViewById(R.id.RigReminderIntervalField);
		iField.setOnClickListener(intervalEditListener);
		updateInterval(interval, intervalUnit);
		
		// init last done date
		TextView ldField = (TextView) getActivity().findViewById(R.id.RigReminderLastDoneField);
		ldField.setOnClickListener(dateEditListener);
		updateLastDoneDate(lastDoneDate);
		
		// add button listeners
		ImageButton saveButton = (ImageButton) getActivity().findViewById(R.id.RigReminderSaveButton);
		saveButton.setOnClickListener(saveListener);
		
		ImageButton cancelButton = (ImageButton) getActivity().findViewById(R.id.RigReminderCancelButton);
		cancelButton.setOnClickListener(cancelListener);
		
		ImageButton deleteButton = (ImageButton) getActivity().findViewById(R.id.RigReminderDeleteButton);
		deleteButton.setOnClickListener(deleteListener);
		deleteButton.setVisibility(isEdit ? View.VISIBLE : View.GONE);
	}
	
	private void showIntervalDialog()
	{
		// create dialog
		TimeIntervalDialog dialog = new TimeIntervalDialog(
				getActivity(),
				interval,
				intervalUnit,
				intervalSetListener);
		// show
		dialog.show();
	}
	
	private void showDateDialog()
	{
		// create date dialog
		Calendar cal = Calendar.getInstance();
		cal.setTime(lastDoneDate);
		DatePickerDialog dialog = new DatePickerDialog(
				getActivity(),
				dateSetListener,
				cal.get(Calendar.YEAR),
				cal.get(Calendar.MONTH),
				cal.get(Calendar.DAY_OF_MONTH));
		// show dialog
		dialog.show();
	}
	
	private void updateInterval(int interval, TimeUnit timeUnit)
	{
		// update local vars
		this.interval = interval;
		this.intervalUnit = timeUnit;
		
		// update ui
		TextView iField = (TextView) getActivity().findViewById(R.id.RigReminderIntervalField);
		iField.setText(MessageFormat.format("{0} {1}",
				FormatUtility.toNumericString(interval),
				getString(intervalUnit.getResourceId())));
		
		// update due by
		updateDueByField();
	}
	
	private void updateLastDoneDate(Date date) 
	{
		// update date
		this.lastDoneDate = date;
		
		// update ui
		TextView ldField = (TextView) getActivity().findViewById(R.id.RigReminderLastDoneField);
		ldField.setText(FormatUtility.toDateString(getActivity(), lastDoneDate));
		
		// update due by
		updateDueByField();
	}
	
	private void updateDueByField()
	{
		// get due date and due status
		Date dueDate = RigReminder.getDueDate(interval, intervalUnit, lastDoneDate);
		DueStatus dueStatus = RigReminder.getDueStatus(dueDate);
		
		// update due by field
		TextView dbField = (TextView) getActivity().findViewById(R.id.RigReminderDueByField);
		dbField.setText(FormatUtility.toDateString(getActivity(), dueDate));
		
		// update color/icon
		Drawable icon = null;
		int textStyleId = R.style.FormFieldValueStyle;
		if (dueStatus == DueStatus.DueSoon)
		{
			textStyleId = R.style.DueSoonTextStyle;
		}
		else if (dueStatus == DueStatus.PastDue)
		{
			textStyleId = R.style.PastDueTextStyle;
			icon = getResources().getDrawable(R.drawable.skull_small);
		}
		dbField.setTextAppearance(getActivity(), textStyleId);
		dbField.setCompoundDrawablesWithIntrinsicBounds(null, null, icon, null);
	}

	private void commitChanges()
	{
		// get name from field
		EditText dField = (EditText) getActivity().findViewById(R.id.RigReminderDescriptionField);
		name = dField.getText().toString();
	}
	
	private void save()
	{
		commitChanges();
		
		// set result
		RigReminderNotifier f = (RigReminderNotifier) getFragmentManager().findFragmentByTag(getArguments().getString(Constants.EXTRA_FRAG_TAG));
		f.updateReminder(name, interval, intervalUnit, lastDoneDate);
		
		// finish
		getFragmentManager().popBackStack();
	}
	
	private void delete()
	{
		RigReminderNotifier f = (RigReminderNotifier) getFragmentManager().findFragmentByTag(getArguments().getString(Constants.EXTRA_FRAG_TAG));
		f.deleteReminder();
		
		// finish
		getFragmentManager().popBackStack();
	}
}
